#include "CTextElement.h"
#include <QWidget>
#include <QPainter>
#include <QFont>
#include <QBrush>
#include <QTimer>
#include <QPixmap>
CTextElement::CTextElement(const QString& name, const QString& iPath, const int& index, const QString &cmdKey)
	:LeafElement(iPath, index,cmdKey), _name(name), _iconPath(iPath), _timer(nullptr),
	_drawLength(name.length()), _isDrawFlag(false),_textWidth(240)
{

}


CTextElement::~CTextElement()
{
	if (_timer) {
		delete _timer;
		_timer = nullptr;
	}
}

void CTextElement::drawElement(QWidget* widget, QPainter* painter, bool bSelected, const QRect& rect)
{
	initTimer(widget);
	_isDrawFlag = true;
	this->setRect(rect);
	LeafElement::drawElement(widget, painter, bSelected, rect);
	drawText(painter, bSelected);
	_isDrawFlag = false;
}

void CTextElement::setRect(const QRect& rect)
{
	if (rect.isEmpty())
	{
		if (_timer != nullptr && _timer->isActive())
		{
			_timer->stop();
		}
	}
	UIElement::setRect(rect);
}


void CTextElement::initTimer(QWidget* widget)
{
	if (widget != nullptr && _timer == nullptr) {
		_timer = new QTimer(widget);
		QObject::connect(_timer, &QTimer::timeout, [&]() {
			this->slotTimer();
			});
	}
}
void CTextElement::slotTimer()
{
	if (_isDrawFlag)
	{
		return;
	}
	QWidget* widget = qobject_cast<QWidget*>(_timer->parent());
	_drawLength--;
	if (_drawLength < 0) {
		_drawLength = _name.length();
	}
	widget->update();
}




void CTextElement::drawText(QPainter* painter, bool bSelected)
{
	QFont font;
	if (!bSelected) {

		font.setPixelSize(24);
		font.setFamily("Source Han Sans K");
		painter->setFont(font);
		QPen pen(QColor(255, 255, 255));
		painter->setPen(pen);
	}
	else {
		font.setPixelSize(36);
		font.setFamily("Source Han Sans K");
		painter->setFont(font);
		QPen pen(QColor(10, 132, 255));
		painter->setPen(pen);
	}

	QFontMetrics metrics(font);
	QString text(getTranslate(_name));
	int w = metrics.width(text);
	 
	QRect textRect = QRect(_rect.topLeft() , QSize(std::min(w, _textWidth), metrics.height()));
	if (w > _textWidth && _timer != nullptr) {
		if (_timer != nullptr) {
			if (!_timer->isActive()) {
				_timer->start(_timerInterval);
			}
		}
		if (!bSelected) {
			painter->drawText(textRect, Qt::AlignLeft | Qt::AlignVCenter, text.right(_drawLength));
		}else {
			painter->drawText(textRect, Qt::AlignLeft, text.right(_drawLength));
		}
		
		if (_otherInfo.toInt() == _index) {
			QPixmap pixmap(":/UI/icon/common/select.png");
			if (pixmap.isNull()) {
				return;
			}
			painter->drawPixmap(QRect(textRect.topRight() + QPoint(16, 3), pixmap.size()), pixmap);
		}
	}
	else
	{
		if (!bSelected) {
			painter->drawText(textRect, Qt::AlignLeft | Qt::AlignVCenter, text);
		}
		else
		{
			painter->drawText(textRect, Qt::AlignLeft, text);
		}

		if (_otherInfo.toInt() == _index) {
			QPixmap pixmap(":/UI/icon/common/select.png");
			if (pixmap.isNull()) {
				return;
			}
			painter->drawPixmap(QRect(textRect.topRight() + QPoint(16, 3), pixmap.size()), pixmap);
		}
	}

}
